package com.ruoyi.aitcommon.service;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.aitcommon.utils.ExceptionUtils;
import com.ruoyi.aitcommon.utils.JSONResult;
import com.ruoyi.aitcommon.utils.ObjUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class ResultService {
    /**
     * 检查数据是否为空
     * @param datas 数据
     * @param errMsg 非空报错信息
     * @return
     */
    public JSONObject checkBlank(List<Map<String,Object>> datas,String errMsg) {
        try {
            if(ObjUtils.isNotBlank(datas))
                throw new Exception(errMsg);
            return JSONResult.success();
        } catch (Exception ex) {
            return JSONResult.error(ex.getMessage());
        }

    }
    /**
     * EntityInfo中的数据检查,用于同步调用flow后的数据检查
     * @param datas EntityInfo返回数据
     * @param retCodeField EntityInfo中返回结果字段,如retCode
     * @param retMsgField EntityInfo中返回结果字段,如retMsg
     * @return flow返回JSONResult
     */
    public JSONObject checkEntityInfo(List<Map<String,Object>> datas, String retCodeField, String retMsgField) {
        try {
            if(ObjUtils.isBlank(datas))
                throw new Exception("处理数据为空!");

            Map<String,Object> last=null;
            for (Map<String,Object> item:datas){
                if(!item.containsKey(retCodeField))
                    ExceptionUtils.throwException(null, "处理数据不存在字段[{}]",retCodeField);
                if(!item.containsKey(retMsgField))
                    ExceptionUtils.throwException(null, "处理数据不存在字段[{}]",retMsgField);

                final Object retCode = item.get(retCodeField);
                if(retCode.equals("失败"))
                    ExceptionUtils.throwException(null,"处理数据返回错误[{}]",item.get(retMsgField));
                last=item;
            }
            return JSONResult.success(last.get(retMsgField));
        } catch (Exception ex) {
            return JSONResult.error(ex.getMessage());
        }
    }
}
